package dao.imp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;


import dao.UserDAO;
import model.User;
import util.DBConnection;

public class UserDAOImp implements UserDAO{
	
	private static final String FIND_ALL_USER = "select * from user ";
	private static final String FINDBYEMAIL = "select * from user where email=?";
	
	@SuppressWarnings("finally")
	@Override
	public List<User> findAll() throws Exception {
		Connection conn = null;
		PreparedStatement prep = null;
		ResultSet rs = null;
		List<User> resultList = null;
		try {
			conn = DBConnection.getConnection();
			prep = conn.prepareStatement(FIND_ALL_USER);
			rs = prep.executeQuery();
			resultList = new ArrayList<User>();
			User user = null;
			while (rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setEmail(rs.getString("email"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				user.setUserIntegral(rs.getInt("user_integral"));
				user.setEmailVerify(rs.getBoolean("is_email_verify"));
				user.setEmailVerifyCode(rs.getString("email_verify_code"));
				user.setPosition(rs.getString("position"));
				resultList.add(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(rs, prep, conn);
			return resultList;
		}
	}

	@Override
	public User findByEmail(String email) throws Exception {
		PreparedStatement prep = null;
		Connection conn = null;
		User u = null;
		ResultSet rst = null;
		try{
			conn = DBConnection.getConnection();
			prep = conn.prepareStatement(FINDBYEMAIL);
			prep.setString(1, email);
			rst	= prep.executeQuery();
	        if(rst.next()) {
				u = new User();
				u.setEmail(rst.getString("email"));
				u.setEmailVerifyCode(rst.getString("email_verify_code"));
				u.setId(rst.getInt("id"));
//				u.setLastLoginIp(rst.getString("last_login_ip"));
//				u.setLastLoginTime(rst.getLong("last_login_time"));
				u.setName(rst.getString("name"));
				u.setPassword(rst.getString("password"));
				u.setUserIntegral(rst.getInt("user_integral"));
				String is_email_verify = rst.getString("is_email_verify");
				if(is_email_verify.equals("T")) {
					u.setEmailVerify(true);
				} else{
					u.setEmailVerify(false);
				}
			}
		} finally {
			DBConnection.close(prep, conn);
		}
		return u;
	}

	@Override
	public void update(User u) throws Exception {
		// TODO Auto-generated method stub
		
	}
}
